package drp.snowbell.util.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import drp.snowbell.util.StrHelper;


/**
 * 文件工具类
 * 
 * @author woj
 * 
 */
public class FileUtility {

	public static void save(String path, byte[] data) throws IOException {
		File file = getFile(path);

		FileOutputStream outStream = new FileOutputStream(file);
		outStream.write(data);
		outStream.flush();
		outStream.close();
	}

	public static void save(String path, String stringData) throws IOException {
		File file = getFile(path);

		FileWriter fw = new FileWriter(file);
		fw.write(stringData);
		fw.flush();
		fw.close();
	}

	/**
	 * 分割路径的目录部分和文件名部分
	 * 
	 * @param path
	 *            路径
	 * @return 返回字符串数组.Sting[0]为目录.String[1]为文件名
	 */
	public static String[] splitDirAndFile(String path) {
		String[] ret = null;
		if (!StrHelper.isNullOrEmpty(path)) {
			ret = new String[2];
			int index = path.lastIndexOf(File.separatorChar);
			if (index > 0) {
				ret[0] = path.substring(0, index);
				int nameIndex = index + 1;
				if (nameIndex >= path.length()) {
					ret[1] = "";
				} else {
					ret[1] = path.substring(nameIndex);
				}

			} else if (index == 0) {
				ret[0] = "";
				if (path.length() > 1) {
					ret[1] = path.substring(1);
				} else {
					ret[1] = "";
				}
			} else {
				ret[0] = "";
				ret[1] = path;
			}
		}
		return ret;
	}

	/**
	 * 修正相对路径的格式.相对路径是相对于系统根目录
	 * 
	 * @param path
	 * @return 根据本地文件分割符号分割.而且开头必须为separatorChar
	 */
	public static String prettyRelativePath(String path) {
		String ret = path;
		if (!StrHelper.isNullOrEmpty(ret)) {
			if (File.separatorChar == '\\') {
				ret = ret.replaceAll("/", "\\\\");
				if (ret.charAt(0) != '\\') {
					ret = '\\' + ret;
				}
			} else if (File.separatorChar == '/') {
				ret = ret.replaceAll("\\\\", "/");
				if (ret.charAt(0) != '/') {
					ret = '/' + ret;
				}
			}
		}
		return ret;
	}

	public static File getFile(String path) {
		return new File(path);
	}
}
